<template>
  <div>
        <!--   面包屑导航   -->
      <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>用户管理</el-breadcrumb-item>
          <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
        <!--   卡片区域   -->
      <el-card>
        <!--    上行搜索框区域      -->
          <el-row :gutter="20">
              <el-col :span="7">
                  <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                      <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                  </el-input>
              </el-col>
              <el-col :span="5"><el-button type="primary" @click="dialogVisible=true">添加用户</el-button></el-col>
          </el-row>
        <!--    下行table列表区域      -->
          <el-table :data="users" border stripe style="width: 100%">
              <el-table-column type="index"></el-table-column>
              <el-table-column prop="username" label="姓名" ></el-table-column>
              <el-table-column prop="email" label="邮箱" ></el-table-column>
              <el-table-column prop="mobile" label="电话" ></el-table-column>
              <el-table-column prop="role_name" label="角色" ></el-table-column>
              <el-table-column  label="状态">
                <!--  可以利用作用域插槽来过去本行的数据    -->
                  <template slot-scope="scope">
               <!--  在此处可以打印本行所加载的数据  {{scope.row}}  -->
                    <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
                  </template>
              </el-table-column>
              <el-table-column  label="操作" >
                <!--  同样是利用作用域插槽对渲染 -->
                  <template slot-scope="scope">
                      <el-button type="primary" icon="el-icon-edit" size="mini" @click="editInfo(scope.row.id)"></el-button>
                      <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUserInfo(scope.row.id)"></el-button>
                      <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
                          <el-button type="warning" icon="el-icon-setting" size="mini" @click="settingUser(scope.row)"></el-button>
                      </el-tooltip>
                  </template>
              </el-table-column>
          </el-table>
        <!--     底部分页区     -->
          <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page=queryInfo.pagenum
                  :page-sizes="[1, 2, 5, 10]"
                  :page-size=queryInfo.pagesize
                  layout="total, sizes, prev, pager, next, jumper"
                  :total=total>
          </el-pagination>
      </el-card>
        <!--   添加用户对话框   -->
      <el-dialog
              title="新增用户信息"
              :visible.sync="dialogVisible"
              width="50%"
              @close="closeDialog"
              >
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px">
              <el-form-item label="用户名" prop="username">
                  <el-input v-model="ruleForm.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                  <el-input v-model="ruleForm.password" type="password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="ruleForm.email" type="email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                  <el-input v-model="ruleForm.mobile"></el-input>
              </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser">确 定</el-button>
          </span>
      </el-dialog>
        <!-- 修改用户信息对话框  -->
      <el-dialog
              title="提示"
              :visible.sync="editDialogVisible"
              width="50%" @close="editClose">
          <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
              <el-form-item label="用户名">
                  <el-input v-model="editForm.username" disabled></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="editForm.email"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="editForm.mobile"></el-input>
              </el-form-item>
          </el-form>
          <span slot="footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editUserInfo">确 定</el-button>
          </span>
      </el-dialog>
        <!--  修改用户身份    -->
      <el-dialog
              title="分配角色"
              :visible.sync="setUserDialogVisible"
              width="50%"
              @close="closeRoleDialog">
          <div>
              <p>当前用户：{{userInfo.username}}</p>
              <p>当前角色：{{userInfo.role_name}}</p>
              <p>
                  分配新角色：
                  <el-select v-model="newRole" placeholder="请选择">
                      <el-option
                              v-for="item in allRolseList"
                              :key="item.id"
                              :label="item.roleName"
                              :value="item.id">
                      </el-option>
                  </el-select>
              </p>
          </div>
          <span slot="footer" class="dialog-footer">
    <el-button @click="setUserDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="supportNewRole">确 定</el-button>
  </span>
      </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "user",
        data(){
            //邮箱的校验规则
            var emailRules = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('邮箱不能为空'));
                }
                const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
                 if(regEmail.test(value)){
                     return  callback()
                 }
                 callback(new Error('请输入合法的邮箱'))
            };
            //验证手机号规则
            var checkMobile=(rule, value, callback)=>{
                if (!value) {
                    return callback(new Error('手机号不能为空'));
                }
                const regMobile=/^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
                if(regMobile.test(value)){
                    return  callback()
                }
                callback(new Error('请输入合法的手机号'))

            }
            return{
                queryInfo:{
                    query:"",
                    pagenum:1,
                    pagesize:2
                },
                total:0,
                users:[],
                dialogVisible:false,
                editDialogVisible:false,
                //按id查询出的修改数据
                editForm:{},
                //编辑用户规则
                editFormRules:{
                    email:[
                        //运用自定义校验规则
                        { validator:emailRules, trigger: 'blur' },
                    ],
                    mobile:[
                        {  validator:checkMobile, trigger: 'blur' },
                    ]
                },
                //添加用户绑定数据
                ruleForm:{
                    username:"",
                    password:"",
                    email:"",
                    mobile:""
                },
                //添加用户定义规则
                rules:{
                    username:[
                        { required: true, message: '请输入用户名', trigger: 'blur' },
                        { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                    ],
                    password:[
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                    ],
                    email:[
                        //运用自定义校验规则
                        { validator:emailRules, trigger: 'blur' },
                    ],
                    mobile:[
                        {  validator:checkMobile, trigger: 'blur' },
                    ]
                },

                //分配用户角色
                setUserDialogVisible:false,
                //加载出来的角色数据
                allRolseList:[],
                //具体行的用户数据
                userInfo:{},
                //已选中的角色id
                newRole:""
            }
        },
        created() {
            this.getUserList()
        },
        methods:{
            //获取用户信息
            async getUserList(){
                var {data}=await this.$http.get('users',{params:this.queryInfo})
                this.total=data.data.total
                this.users=data.data.users
            },
            //获取最新的pagesize
            handleSizeChange(newSize){
                this.queryInfo.pagesize=newSize
                this.getUserList()
            },
            //获取最新页数
            handleCurrentChange(currentNum){
                this.queryInfo.pagenum=currentNum
                this.getUserList()
            },
            //监听swith的状态改变并发送到数据库修改
            async switchChange(userInfo){
                var {data}=await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
                if(data.meta.status!==200){
                    userInfo.mg_state=!userInfo.mg_state
                    return this.$message.error(data.meta.msg)
                }
                this.$message.success('修改状态成功')
            },
            //添加用户对话框关闭
            closeDialog(){
                this.$refs.ruleForm.resetFields()
            },
            //添加用户
            addUser(){
                this.$refs.ruleForm.validate(async vaild=>{
                    if(!vaild)return this.$message.error('用户信息规则错误')

                    var {data:res}=await this.$http.post('users',this.ruleForm)

                    if (res.meta.status!==201)return this.$message.error('用户注册失败')
                    this.$message.success('用户注册成功')

                    //关闭提示框
                    this.dialogVisible=false
                    //重新请求数据
                    this.getUserList()
                })
            },
            //修改用户对话框
            async editInfo(id){
                var {data:res}=await this.$http.get('users/'+id)
                if (res.meta.status!==200)return this.$message.error('修改数据错误')
                this.editForm=res.data
                this.editDialogVisible=true
            },
            //监听编辑用户对话框关闭事件
            editClose(){
                this.$refs.editFormRef.resetFields()
            },
            //修改用户的编辑提交数据
            editUserInfo(){
                this.$refs.editFormRef.validate(async vaild=>{
                    if(!vaild)return this.$message.error('修改信息规则错误')

                    var {data:res}=await this.$http.put('users/'+this.editForm.id,{
                        email:this.editForm.email,
                        mobile:this.editForm.mobile
                    })

                    if (res.meta.status!==200)return this.$message.error('用户更新信息失败')

                    this.$message.success('更新用户信息成功')
                    //关闭提示框
                    this.editDialogVisible=false
                    //重新请求数据
                    this.getUserList()
                })
            },
            //删除用户信息，并生成提示框
            async delUserInfo(id){
                //弹出提示框询问用户是否删除
                var result=await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err=>err)
                //点确定之后result就为confirm
                //点取消之后返回cancel
                if(result!=='confirm')return this.$message.info('取消删除')

                //根据id发送删除id数据项请求
                var {data:res}=await this.$http.delete('users/'+id)
                if (res.meta.status!==200)return this.$message.error('删除用户失败！')
                this.$message.success('删除用户成功！')
                this.getUserList()
            },

            //分配用户角色
            async settingUser(userInfo){
                //获取当前角色信息
                this.userInfo=userInfo
                //获取所有的角色的信息
                var {data:res}=await this.$http.get('roles')
                if (res.meta.status!==200)return this.$message.error('获取信息失败')
                this.allRolseList=res.data
                this.setUserDialogVisible=true
            },
            //提供新修改的角色
            async supportNewRole(){
                if(!this.newRole){
                    return this.$message.info('没有选择的角色')
                }
                var {data:res}=await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.newRole})
                if (res.meta.status!==200)return this.$message.error('选择新角色失败')
                this.$message.success('选择新角色成功')
                this.getUserList()
                this.setUserDialogVisible=false
            },
            //关闭分配角色窗口
            closeRoleDialog(){
                this.newRole=""
                this.userInfo={}
            }

        }
    }
</script>

<style scoped>

</style>